<!--卓智达 群组用户列表 -->
<template>
  <div>
    <div style="display: flex;flex-direction: row-reverse">
<!--      <div style="width: 100px">-->
      <div style="width: 100px">
        <Button style="margin-left: 3px" :title="$t('search')" icon="md-search" @click="search"></Button>
        <Button style="margin-left: 3px" :title="$t('new_group')" :disabled="!canEdit" icon="md-add" @click="newGroup"></Button>
        <Button style="margin-left: 3px" v-if="1===0" :title="$t('talk_user_manage')" :disabled="!canEdit" icon="md-people" @click="userManage"></Button>
      </div>
      <div style="width: 100%">
        <Input id="input-device-search"  clearable v-model="srhValue" @on-search="search" :placeholder="$t('keyword')" />
      </div>

      <Row :gutter="1">
        <Col span="20">

        </Col>
      </Row>
    </div>

    <Tree id="group-user-tree"
          :data="dataList"
          :load-data="loadData"
          :render="renderContent"
          :select-node="selectNode"
          @on-select-change="changeNode" expand-node ></Tree>

    <ZzdGroupEdit ref="zzdGroupEdit"/>
    <ZzdGroupUserManager ref="zzdGroupUserManager"/>
  </div>
</template>
<script>
import Zzd from '@/api/Zzd';
import ZzdGroupUserTreeButtons from "@/view/zzd/ZzdGroupUserTreeButtons"
import ZzdGroupEdit from "@/view/zzd/ZzdGroupEdit";
import ZzdGroupUserManager from "@/view/zzd/ZzdGroupUserManager";
import {apiResult, getLoginUser} from "@/libs/util";
import AuthCheck from '@/api/AuthCheck';
export default {
  components:{ZzdGroupUserTreeButtons,ZzdGroupEdit,ZzdGroupUserManager},
  name: "ZzdGroupUserTree",
  data(){
    return{
      canModify:false,
      api: new Zzd(),
      dataList:[],
      srhValue:null,
      selectNode: false,
      canEdit: false
    }
  },
  methods:{
    /**
     * 新群组
     */
    newGroup(){
      this.$refs.zzdGroupEdit.openDialog("ADD",
        {groupName:null,contactName:null,contactPhone:null,id:null,},()=>{
        //回调
          this.keyword=null;
          this.top();
        })

      this.$emit('usr-node-click', "newGroup",null, null)
    },
    top(){
      const that = this;
      const msg = this.$Message.loading({content: this.$t('wait_loading_message'),duration: 10});
      this.api.findGroupUserTree(null).then(res=>{
        setTimeout(msg, 100); //关闭正加载条
          apiResult(res.data,false,result=>{
            this.dataList = this.resoleData(result.data);
          });
      });
    },
    loadData(item, callback){
      const that = this;
      let param = {pid:item.id};
      this.loading = true;
      const msg = this.$Message.loading({content: this.$t('wait_loading_message'),duration: 10});
      this.api.findGroupUserTree(param).then(res=>{
        setTimeout(msg, 100);
        this.loading = false;
          apiResult(res.data,false,result=>{
            const data1 = this.resoleData(result.data)
            //console.log("ZzdGroupUserTree.loadData data=%o",data1)
            callback(data1);
            this.$emit("device-refresh",this.deviceData);
          })
      });

    },
    search(){
      this.top();
    },
    /**
     * 数据转换
     * @param originList  原数据
     */
    resoleData(dataList){
      let target = [];
      if (!!dataList){
        let gpsData=null;
        for(let i in dataList){
          let data = new Object();
          data.id=dataList[i].id;
          data.title=dataList[i].title;
          data.type=dataList[i].type;
          if (data.type === "usr"){
            data.online = dataList[i].online;
          }

          if (!!(dataList[i].children)){
            data.loading=false;
            data.children=[];
          }
          if (!!(dataList[i].arrt)){
            data.arrt=dataList[i].arrt;
          }
          target.push(data);
        }
      }
      return target;
    },
    renderContent(h, { root, node, data }){
      if (data.type === 'grp'){
        return (
          <Poptip trigger="hover" placement="right" width="160" props={{transfer:true}}>
            <span class="node-group-span-1" title={data.title}
                  onclick={()=>{
                    this.$emit('grp-node-click', node, data)
                  }}>{data.title}
            </span>
            <div className="poptip-group-div" slot="content">
              <ZzdGroupUserTreeButtons props={{type:'grp'}}
                                       onBtnClick={(event)=>{ //需要这么写，对应的是组件<PoptipBtn> this.$emit('btnClick', event)
                                         this.handle(event,data);
                                         this.$emit('usr-node-click',event,node, data)
                                       }}
              />
            </div>
          </Poptip>
        )
      }else if (data.type === 'usr' && ('1' === data.online)){
        /** 在线的通道 */
        return(
          <Poptip trigger="hover" placement="right" width="40" props={{transfer:true}}>
            <span class="user-span-online" title={data.title}
                  onclick={()=>{
                    this.handle(event,data);
                    this.$emit('usr-node-click', "locate",node, data)
                  }}
            >{data.title}</span>
            <div class="poptip-group-div" slot="content">
              <ZzdGroupUserTreeButtons props={{type:'usr',thisPlatForm:!!data.arrt.deviceId}}
                         onBtnClick={(event)=>{ //需要这么写，对应的是组件<PoptipBtn> this.$emit('btnClick', event)
                           this.handle(event,data);
                           this.$emit('usr-node-click',event,node, data)
                         }}
              >
              </ZzdGroupUserTreeButtons>
            </div>
          </Poptip>
        )
      }else{
        return (
          <Poptip trigger="hover" placement="right" width="40" props={{transfer:true}}>
            <span class="user-span-offline" title={data.title}
                  onclick={()=>{
                    this.handle(event,data);
                    this.$emit('usr-node-click', "locate",node, data)
                  }}
            >{data.title}</span>
            <div class="poptip-group-div" slot="content">
              <ZzdGroupUserTreeButtons props={{type:'usr',thisPlatForm:!!data.arrt.deviceId}}
                         onBtnClick={(event)=>{ //需要这么写，对应的是组件<PoptipBtn> this.$emit('btnClick', event)
                           this.handle(event,data);
                           this.$emit('usr-node-click', event,node, data)
                         }}
              >
              </ZzdGroupUserTreeButtons>
            </div>
          </Poptip>
        )
      }
    },

    handle(event,data){
      /**
       * delGroup 删除群组
       * clearFromGroup 清空下的用户
       * addToGroup 加入用户到群组
       * removeUser 从群级中移除用户
       */
      console.log("event=%o,data=%o",event,data)
      if (event === "delGroup"){
        //删除群组
        this.$Modal.confirm({title: this.$t('delete_confirm'),content: this.$t('delete_make_sure')+"["+data.arrt.name+"]",
          onOk: () => {
            this.api.deleteGroup(data.arrt.id).then(res=>{
                apiResult(res.data,true,result=>{
                  this.top();
                })
              });
          },
          onCancel:()=>{}
        });
      }else if (event==="userManage"){

      }else if (event === "addToGroup"){
        //加入新用户 加入用户到群组
        //用户管理
        let users=[]
        this.$refs.zzdGroupUserManager.openDialog("group",data.arrt.id);
      }else if (event === "clearFromGroup"){
        console.log("ZzdGroupUserTree.clearFromGroup() = %o",data)
        if (!data.children || data.children.length===0){
          this.$Message.error(this.$t("none_data_to_manipulate"));
          return;
        }
        let params = []
        data.children.forEach((item)=>{
          if (!!item.arrt && !!item.arrt.deviceId){
            params.push(
              {
                groupId:item.arrt.groupId,
                groupIds:item.arrt.groupIds,
                userId:item.arrt.userId,
                userAccount: item.arrt.userAccount}
            )
          }
        });
        console.log("ZzdGroupUserTree.clearFromGroup() = %o",params);
        if (!params || params.length===0){
          this.$Message.error(this.$t("none_data_to_manipulate"));
          return;
        }
        this.$Modal.confirm({title: this.$t('delete_confirm'),content: this.$t('delete_make_sure_by_select'),
          onOk: () => {
            const msg = this.$Message.loading({content: this.$t('wait_dispose_message'),duration: 10});
            this.api.removeFromGroupAndDelete(JSON.stringify(params)).then(res=>{
              setTimeout(msg, 100); //关闭正加载条
              apiResult(res.data,true,result=> {
                this.top();
              })
            });
          },
          onCancel:()=>{}
        });

      }else if (event === "removeUser"){
        //从群组中移除用户
        if (!data.arrt.deviceId){return;}
        this.$Modal.confirm({title: this.$t('delete_confirm'),content: this.$t('delete_make_sure_by_select'),
          onOk: () => {
            const params= [{
              groupId:data.arrt.groupId,
              groupIds:data.arrt.groupIds,
              userId:data.arrt.userId,
              userAccount: data.arrt.userAccount}]
            const msg = this.$Message.loading({content: this.$t('wait_dispose_message'),duration: 10});
            this.api.removeFromGroupAndDelete(JSON.stringify(params)).then(res=>{
              setTimeout(msg, 100); //关闭正加载条
              apiResult(res.data,true,result=> {
                this.top();
              })
            });
          },
          onCancel:()=>{}
        });
      }

    },
    userManage(){
      //用户管理
      this.$refs.zzdGroupUserManager.openDialog("user",null);

    },
    changeNode(){}
  },
  mounted() {
    //console.log(">>>>>> ZzdGroupUserTree。Mounted")
    const userInfo = getLoginUser();
    //console.log(">>>>>> userInfo=%o",userInfo)
    const userLoginName=!!userInfo?userInfo.loginName:"";//  this.$store.getters.getFullName;
    //this.canEdit = userLoginName === "admin" || userLoginName === "Admin" || userLoginName === "super";
    this.canEdit = new AuthCheck().commandDispatchGroupTalk() || userInfo.permissionLevel>=4;

    this.top();
    this.$nextTick(()=>{
    })
  }
}
</script>
<style lang="less">
//@import "src/components/topnav/GbOrgDeviceTree-bright";
.node-group-span-1{
  display: inline-block;
  width: 100%;
  color: #000000 ;
  //font-Weight: bold;
  font-size:18px ;
}

.poptip-group-div{
  //background-color: #0c0c0c;
  margin-left: 0px;
  display: block;
  .btn{
    margin-left: 5px;
  }
}

//在线通道
.user-span-online{
  display: inline-block;
  width: 100%;
  font-Weight:bold;
  color: green;
  font-size:18px ;
}
//离线通道
.user-span-offline{
  display: inline-block;
  width: 100%;
  font-Weight:bold;
  color: #aeaeae;
  font-size:18px ;
}
</style>
